package main
 
import (
  "flag"
  "log"
  //"fmt"
  "time"
  //"sync"
  //"encoding/json"
  "io/ioutil"
  "net/http"
  "github.com/prometheus/client_golang/prometheus/promhttp"
  //"github.com/prometheus/client_golang/prometheus"
  "gopkg.in/yaml.v2"
  "github.com/labstack/echo/v4"
  "github.com/labstack/echo/v4/middleware"
)

type ST_Config struct {
	Exporter struct {
    Osenv string `yaml:"osenv"`
		Namespace string `yaml:"namespace"`
		Scrapeperiod int64 `yaml:"scrapeperiod"`
	} `yaml:"exporter"`
	Metriclabels []struct {
      Subsystem string `yaml:"subsystem"`
      Metrics []struct{
        Name string `yaml:"name"`
        Help string `yaml:"help"`
        Tag string `yaml:"tag"`
        ShellCmd string `yaml:"shcmd"`
      } `yaml:"metrics"`
  } `yaml:"metriclabels"`
}

var (
	// Name is the name of the compiled software.
	Name string = "shell-exporter"
	// Version is the version of the compiled software.
	Version string = "1.0-alpha"
  
  GlobalConfig *ST_Config
  flagconf string
)

func load_config_file(f string) *ST_Config {
  dat,err := ioutil.ReadFile(f)
  if err != nil {
    log.Println(err.Error())
    return nil
  }

  var cfg ST_Config
  err = yaml.Unmarshal(dat, &cfg)
  if err != nil {
    log.Println(err.Error())
    return nil
  }
  return &cfg
}


func handler_healthy(c echo.Context) error {
    return c.String(http.StatusOK, "ok")
}

func init() {
	flag.StringVar(&flagconf, "conf", "config.yaml", "config path, eg: -conf config.yaml")

  flag.Parse()
  GlobalConfig = load_config_file(flagconf)
  //log.Println(GlobalConfig)
}


func main() {

  Initialize_GaugeVec_List()
  MustRegister_GaugeVec_List()

  go func() {
    for {
      ConstructMetric()
      // delay
      time.Sleep( time.Second * time.Duration(GlobalConfig.Exporter.Scrapeperiod) )
    }
  }()

  e := echo.New()

  // exe_dir,_ := filepath.Abs(filepath.Dir(os.Args[0]))
  // assets_dir:=exe_dir+"/"+"assets"
  // log.Println("Web assets directory: ",assets_dir)
  // e.Static("/", exe_dir+"/"+"assets")
  
  // Middleware
  //e.Use(middleware.Logger())
  e.Use(middleware.Recover())
  //e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
  //  Timeout: 30 * time.Second,
  //}))

  // add application routes
  e.GET("/api/v1/healthy", handler_healthy)
  e.GET("/metrics", echo.WrapHandler(promhttp.Handler()) )

  // Start server
  log.Println("Echo Service is running.")
  //e.Logger.Fatal(e.Start(":9314"))
  e.Start(":9314")

}
